package com.sunshine.lnuplus.view.TimetableSetting;

import android.annotation.SuppressLint;
import android.app.DatePickerDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.DatePicker;
import android.widget.SeekBar;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.databinding.DataBindingUtil;
import androidx.lifecycle.Observer;
import androidx.lifecycle.ViewModelProviders;

import com.google.android.material.snackbar.Snackbar;
import com.sunshine.lnuplus.R;
import com.sunshine.lnuplus.databinding.ActivityTimetableSettingBinding;
import com.sunshine.lnuplus.utils.DialogFragmentHelper;
import com.sunshine.lnuplus.utils.FileHelper;
import com.sunshine.lnuplus.utils.StatusBarUtils;
import com.sunshine.lnuplus.utils.TagHelper;
import com.sunshine.lnuplus.utils.TimeHelper;
import com.sunshine.lnuplus.view.BaseActivity;
import com.sunshine.lnuplus.view.Timetable.TimetableFragment;

public class TimetableSettingActivity extends BaseActivity implements SeekBar.OnSeekBarChangeListener, View.OnClickListener {
    private ActivityTimetableSettingBinding binding;
    private TimetableSettingViewModel viewModel;
    private DialogFragmentHelper save,toDefault,dialogFragmentHelper;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        binding = DataBindingUtil.setContentView(this, R.layout.activity_timetable_setting);
        viewModel = ViewModelProviders.of(this).get(TimetableSettingViewModel.class);

        if(viewModel.isEverydayBackground()) FileHelper.setBackground(this, binding.timetableSettingBackground);
        StatusBarUtils.with(this).init();
        getSupportActionBar().setBackgroundDrawable(getResources().getDrawable(R.color.transparent));
        getSupportActionBar().setDisplayHomeAsUpEnabled(true);
        getSupportActionBar().setHomeButtonEnabled(true);

        loadData();
    }

    private void loadData(){
        View view = LayoutInflater.from(this).inflate(R.layout.dialog_progress,null);
        TextView textView = view.findViewById(R.id.progress_text);
        textView.setText("界面加载中，稍安勿躁~");
        dialogFragmentHelper = DialogFragmentHelper.newInstance("加载中",null,null,view,false,null,null);
        dialogFragmentHelper.show(getSupportFragmentManager(),"");
        handler.sendEmptyMessage(2);
    }

    private void initTimetable() {
        binding.timetableSettingLayout
                .initTimetable()
                .addLesson("测试课程1", "老师", "教室", "1-1", "0", "1")
                .addLesson("测试课程2", "老师", "教室", "2-1", "0", "2")
                .addLesson("测试课程3", "老师", "教室", "3-1", "0", "1")
                .addLesson("测试课程4", "老师", "教室", "4-1", "0", "2")
                .addLesson("测试课程5", "老师", "教室", "5-1", "0", "1")
                .addLesson("测试课程6", "老师", "教室", "1-2", "0", "2")
                .addLesson("测试课程7", "老师", "教室", "2-2", "0", "1")
                .addLesson("测试课程8", "老师", "教室", "3-2", "0", "2")
                .addLesson("测试课程9", "老师", "教室", "4-2", "0", "1")
                .addLesson("测试课程10", "老师", "教室", "5-2", "0", "2");
    }

    @Override
    public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
        switch (seekBar.getId()) {
            case R.id.seekBar_weeksCount:
                if (progress < 1) {
                    progress = 1;
                    Snackbar.make(binding.timetableSetting,"你们学校一学期一周课也没有嘛？",Snackbar.LENGTH_SHORT).show();
                }
                viewModel.getWeeksCount().setValue(progress);
                break;
            case R.id.seekBar_lessonCount:
                if (progress < 2) {
                    progress = 2;
                    Snackbar.make(binding.timetableSetting,"你们学校一天就一节课嘛？",Snackbar.LENGTH_SHORT).show();
                }
                viewModel.getLessonCount().setValue(progress);
                break;
            case R.id.seekBar_heights:
                viewModel.getHeights().setValue(progress);
                break;
            case R.id.seekBar_alpha:
                viewModel.getButtonAlpha().setValue(progress);
                break;
            case R.id.seekBar_radius:
                viewModel.getButtonRadius().setValue(progress);
                break;
            case R.id.seekBar_lesson_button_text_size:
                viewModel.getLessonButtonTextSize().setValue((float) progress);
                break;
            case R.id.seekBar_height_distance:
                viewModel.getButtonHeightDistance().setValue(progress);
                break;
            case R.id.seekBar_width_distance:
                viewModel.getButtonWidthDistance().setValue(progress);
                break;
            case R.id.seekBar_height_padding:
                viewModel.getButtonHeightPadding().setValue(progress);
                break;
            case R.id.seekBar_width_padding:
                viewModel.getButtonWidthPadding().setValue(progress);
                break;
            case R.id.seekBar_timeButtonTextSize:
                viewModel.getTimeButtonTextSize().setValue((float)progress);
                break;
            case R.id.seekBar_dateButtonTextSize:
                viewModel.getDateButtonTextSize().setValue((float) progress);
                break;
        }
    }

    @Override
    public void onStartTrackingTouch(SeekBar seekBar) {
    }

    @Override
    public void onStopTrackingTouch(SeekBar seekBar) {
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.button_showWeekend:
                binding.checkBoxShowWeekend.setChecked(!viewModel.getShowWeekend().getValue());
                viewModel.getShowWeekend().setValue(!viewModel.getShowWeekend().getValue());
                break;
            case R.id.button_showNotInThisWeekLesson:
                binding.checkBoxShowNotInThisWeekLesson.setChecked(!viewModel.getShowNotInThisWeekLesson().getValue());
                viewModel.getShowNotInThisWeekLesson().setValue(!viewModel.getShowNotInThisWeekLesson().getValue());
                break;
            case R.id.button_showTeacher:
                binding.checkBoxShowTeacher.setChecked(!viewModel.getShowTeacher().getValue());
                viewModel.getShowTeacher().setValue(!viewModel.getShowTeacher().getValue());
                break;
            case R.id.button_showLessonTime:
                binding.checkBoxShowLessonTime.setChecked(!viewModel.getShowLessonTime().getValue());
                viewModel.getShowLessonTime().setValue(!viewModel.getShowLessonTime().getValue());
                break;
            case R.id.button_chooseBeginDate:
                int mYear = TimeHelper.getYear(),mMonth = TimeHelper.getMonth()-1,mDayOfMonth = TimeHelper.getDay();
                DatePickerDialog datePickerDialog = new DatePickerDialog(this, new DatePickerDialog.OnDateSetListener() {
                    @Override
                    public void onDateSet(DatePicker view, int year, int month, int dayOfMonth) {
                        viewModel.getBeginDateMonth().setValue(month);
                        viewModel.getBeginDateDay().setValue(dayOfMonth);
                    }
                },mYear,mMonth,mDayOfMonth);
                datePickerDialog.show();
                break;
        }
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.timetable_setting, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()) {
            case R.id.to_save:
                viewModel.toSave(handler);
                break;
            case R.id.to_default:
                initDefaultDialog();
                break;
            case android.R.id.home:
                initSaveDialog();
                break;
        }
        return true;
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if ((keyCode == KeyEvent.KEYCODE_BACK)) {
            initSaveDialog();
            return false;
        }else {
            return super.onKeyDown(keyCode, event);
        }
    }

    private void initSaveDialog(){
        DialogInterface.OnClickListener positive,negative;
        positive = new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                viewModel.toSave(handler);
            }
        };
        negative = new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                setResult(TagHelper.TIMETABLESETTING,new Intent().putExtra("save_success",0));
                finish();
            }
        };
        save = DialogFragmentHelper.newInstance("警告","你要保存所修改的设置吗？","保存","不保存",true,positive,negative);
        save.show(getSupportFragmentManager(),"");
    }

    private void initDefaultDialog(){
        DialogInterface.OnClickListener positive,negative;
        positive = new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                viewModel.toDefault();
                setResult(TagHelper.TIMETABLESETTING,new Intent().putExtra("save_success",1));
                finish();
            }
        };
        negative = new DialogInterface.OnClickListener() {@Override public void onClick(DialogInterface dialog, int which) {}};
        toDefault = DialogFragmentHelper.newInstance("警告","你要恢复所有设置到默认吗？","恢复","再想想",true,positive,negative);
        toDefault.show(getSupportFragmentManager(),"");
    }

    @SuppressLint("HandlerLeak")
    Handler handler = new Handler(){
        @Override
        public void handleMessage(@NonNull Message msg) {
            super.handleMessage(msg);
            if(msg.what==1) {
                setResult(TagHelper.TIMETABLESETTING,new Intent().putExtra("save_success",1));
                finish();
            }
            if(msg.what==2){
                viewModel.getWeeksCount().observe(TimetableSettingActivity.this, new Observer<Integer>() {
                    @Override
                    public void onChanged(Integer integer) {
                        binding.buttonWeeksCount.setText("\t学期总周数：" + integer);
                        binding.seekBarWeeksCount.setProgress(integer);
                        initTimetable();
                    }
                });
                viewModel.getLessonCount().observe(TimetableSettingActivity.this, new Observer<Integer>() {
                    @Override
                    public void onChanged(Integer integer) {
                        binding.buttonLessonCount.setText("\t每天课程节数：" + integer);
                        binding.seekBarLessonCount.setProgress(integer);
                        binding.timetableSettingLayout.setLessonCount(integer);
                        initTimetable();
                    }
                });
                viewModel.getShowWeekend().observe(TimetableSettingActivity.this, new Observer<Boolean>() {
                    @Override
                    public void onChanged(Boolean aBoolean) {
                        binding.checkBoxShowWeekend.setChecked(aBoolean);
                        binding.timetableSettingLayout.setShowWeekend(aBoolean);
                        initTimetable();
                    }
                });
                viewModel.getHeights().observe(TimetableSettingActivity.this, new Observer<Integer>() {
                    @Override
                    public void onChanged(Integer integer) {
                        binding.buttonHeights.setText("\t课程格子高度：" + integer + "dp");
                        binding.seekBarHeights.setProgress(integer);
                        binding.timetableSettingLayout.setHeights(integer);
                        initTimetable();
                    }
                });
                viewModel.getButtonAlpha().observe(TimetableSettingActivity.this, new Observer<Integer>() {
                    @Override
                    public void onChanged(Integer integer) {
                        binding.buttonAlpha.setText("\t课程格子透明度：" + integer);
                        binding.seekBarAlpha.setProgress(integer);
                        binding.timetableSettingLayout.setButtonAlpha(integer);
                        initTimetable();
                    }
                });
                viewModel.getButtonRadius().observe(TimetableSettingActivity.this, new Observer<Integer>() {
                    @Override
                    public void onChanged(Integer integer) {
                        binding.buttonRadius.setText("\t课程格子圆角：" + integer);
                        binding.seekBarRadius.setProgress(integer);
                        binding.timetableSettingLayout.setButtonRadius(integer);
                        initTimetable();
                    }
                });
                viewModel.getLessonButtonTextSize().observe(TimetableSettingActivity.this, new Observer<Float>() {
                    @Override
                    public void onChanged(Float aFloat) {
                        binding.buttonLessonButtonTextSize.setText("\t课程格子文字大小："+aFloat+"dp");
                        binding.seekBarLessonButtonTextSize.setProgress(aFloat.intValue());
                        binding.timetableSettingLayout.setLessonButtonTextSize(aFloat);
                        initTimetable();
                    }
                });
                viewModel.getButtonHeightDistance().observe(TimetableSettingActivity.this, new Observer<Integer>() {
                    @Override
                    public void onChanged(Integer integer) {
                        binding.buttonHeightDistance.setText("\t课程格子纵向外边距：" + integer + "dp");
                        binding.seekBarHeightDistance.setProgress(integer);
                        binding.timetableSettingLayout.setButtonHeightDistance(integer);
                        initTimetable();
                    }
                });
                viewModel.getButtonWidthDistance().observe(TimetableSettingActivity.this, new Observer<Integer>() {
                    @Override
                    public void onChanged(Integer integer) {
                        binding.buttonWidthDistance.setText("\t课程格子横向外边距：" + integer + "dp");
                        binding.seekBarWidthDistance.setProgress(integer);
                        binding.timetableSettingLayout.setButtonWidthDistance(integer);
                        initTimetable();
                    }
                });
                viewModel.getButtonHeightPadding().observe(TimetableSettingActivity.this, new Observer<Integer>() {
                    @Override
                    public void onChanged(Integer integer) {
                        binding.buttonHeightPadding.setText("\t课程格子纵向内边距：" + integer + "dp");
                        binding.seekBarHeightPadding.setProgress(integer);
                        binding.timetableSettingLayout.setButtonHeightPadding(integer);
                        initTimetable();
                    }
                });
                viewModel.getButtonWidthPadding().observe(TimetableSettingActivity.this, new Observer<Integer>() {
                    @Override
                    public void onChanged(Integer integer) {
                        binding.buttonWidthPadding.setText("\t课程格子横向内边距：" + integer + "dp");
                        binding.seekBarWidthPadding.setProgress(integer);
                        binding.timetableSettingLayout.setButtonWidthPadding(integer);
                        initTimetable();
                    }
                });
                viewModel.getShowNotInThisWeekLesson().observe(TimetableSettingActivity.this, new Observer<Boolean>() {
                    @Override
                    public void onChanged(Boolean aBoolean) {
                        binding.checkBoxShowNotInThisWeekLesson.setChecked(aBoolean);
                        binding.timetableSettingLayout.setShowNotInThisWeekLesson(aBoolean);
                        initTimetable();
                    }
                });
                viewModel.getShowTeacher().observe(TimetableSettingActivity.this, new Observer<Boolean>() {
                    @Override
                    public void onChanged(Boolean aBoolean) {
                        binding.checkBoxShowTeacher.setChecked(aBoolean);
                        binding.timetableSettingLayout.setShowTeacher(aBoolean);
                        initTimetable();
                    }
                });
                viewModel.getShowLessonTime().observe(TimetableSettingActivity.this, new Observer<Boolean>() {
                    @Override
                    public void onChanged(Boolean aBoolean) {
                        binding.checkBoxShowLessonTime.setChecked(aBoolean);
                        binding.timetableSettingLayout.setShowLessonTime(aBoolean);
                        initTimetable();
                    }
                });
                viewModel.getTimeButtonTextSize().observe(TimetableSettingActivity.this, new Observer<Float>() {
                    @Override
                    public void onChanged(Float aFloat) {
                        binding.buttonTimeButtonTextSize.setText("\t节数文字大小："+aFloat+"dp");
                        binding.seekBarTimeButtonTextSize.setProgress(aFloat.intValue());
                        binding.timetableSettingLayout.setTimeButtonTextSize(aFloat);
                        initTimetable();
                    }
                });
                viewModel.getDateButtonTextSize().observe(TimetableSettingActivity.this, new Observer<Float>() {
                    @Override
                    public void onChanged(Float aFloat) {
                        binding.buttonDateButtonTextSize.setText("\t日期文字大小："+aFloat+"dp");
                        binding.seekBarDateButtonTextSize.setProgress(aFloat.intValue());
                        binding.timetableSettingLayout.setDateButtonTextSize(aFloat);
                        initTimetable();
                    }
                });
                viewModel.getBeginDateMonth().observe(TimetableSettingActivity.this, new Observer<Integer>() {
                    @Override
                    public void onChanged(Integer integer) {
                        binding.buttonChooseBeginDate.setText("\t设置开学时间（可以判断当前周噢）当前周：第"+ TimeHelper.getThisWeek(viewModel.getBeginDateMonth().getValue(),viewModel.getBeginDateDay().getValue())+"周");
                    }
                });
                viewModel.getBeginDateDay().observe(TimetableSettingActivity.this, new Observer<Integer>() {
                    @Override
                    public void onChanged(Integer integer) {
                        binding.buttonChooseBeginDate.setText("\t设置开学时间（可以判断当前周噢）当前周：第"+ TimeHelper.getThisWeek(viewModel.getBeginDateMonth().getValue(),viewModel.getBeginDateDay().getValue())+"周");
                    }
                });

                binding.seekBarWeeksCount.setOnSeekBarChangeListener(TimetableSettingActivity.this);

                binding.seekBarLessonCount.setOnSeekBarChangeListener(TimetableSettingActivity.this);

                binding.buttonShowWeekend.setOnClickListener(TimetableSettingActivity.this);
                binding.checkBoxShowWeekend.setOnClickListener(TimetableSettingActivity.this);

                binding.seekBarHeights.setOnSeekBarChangeListener(TimetableSettingActivity.this);

                binding.seekBarAlpha.setOnSeekBarChangeListener(TimetableSettingActivity.this);

                binding.seekBarRadius.setOnSeekBarChangeListener(TimetableSettingActivity.this);

                binding.seekBarLessonButtonTextSize.setOnSeekBarChangeListener(TimetableSettingActivity.this);

                binding.seekBarHeightDistance.setOnSeekBarChangeListener(TimetableSettingActivity.this);

                binding.seekBarWidthDistance.setOnSeekBarChangeListener(TimetableSettingActivity.this);

                binding.seekBarHeightPadding.setOnSeekBarChangeListener(TimetableSettingActivity.this);

                binding.seekBarWidthPadding.setOnSeekBarChangeListener(TimetableSettingActivity.this);

                binding.buttonShowNotInThisWeekLesson.setOnClickListener(TimetableSettingActivity.this);

                binding.buttonShowTeacher.setOnClickListener(TimetableSettingActivity.this);

                binding.buttonShowLessonTime.setOnClickListener(TimetableSettingActivity.this);

                binding.seekBarTimeButtonTextSize.setOnSeekBarChangeListener(TimetableSettingActivity.this);

                binding.seekBarDateButtonTextSize.setOnSeekBarChangeListener(TimetableSettingActivity.this);

                binding.buttonChooseBeginDate.setOnClickListener(TimetableSettingActivity.this);

                dialogFragmentHelper.dismiss();
            }
        }
    };

}